"""Generate a hue histogram from an input image.

This simple script uses standard matplotlib and numpy functions to
generate a hue histogram for a given image.

TODO: currently quite slow. improve performance.
"""

import argparse
import colorsys
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np


def main():
  # Parse command line flags
  parser = argparse.ArgumentParser()
  parser.add_argument('input_filename',
                      help='use this as the input for our hue histogram')
  parser.add_argument('output_filename',
                      help='histogram will be stored in this file')
  args = parser.parse_args()

  # Read image and separate to RGB channels
  img = mpimg.imread(args.input_filename)
  r_values = img[:, :, 0].flatten()
  g_values = img[:, :, 1].flatten()
  b_values = img[:, :, 2].flatten()

  # Will hold all hue values in the image (to be plotted later)
  h_values = []

  # Convert to HSV and save the H values
  for r_val, g_val, b_val in zip(r_values, g_values, b_values):
    h_val = colorsys.rgb_to_hsv(r_val / 255.0,
                                g_val / 255.0,
                                b_val / 255.0)[0]
    # We scale the values to be in [0, 2*pi]
    h_values.append(h_val * 2 * np.pi)

  # Create the hue histogram
  plt.hist(h_values, 256, facecolor='g', alpha=0.75)

  # Beautify figure
  plt.xlim(0, 2.0 * np.pi)
  plt.title('Hue Histogram')
  plt.grid(True)

  # Save figure
  plt.savefig(args.output_filename)

if __name__ == '__main__':
  main()
